package com.hc;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLibProxy implements MethodInterceptor {
    private Object target;
    private TransicationManager tx;

    public CGLibProxy(Object target, TransicationManager tx) {
        this.target = target;
        this.tx = tx;
    }

    public Object getProxy(){
        Enhancer enhancer = new Enhancer();
        //设置代理对象的父类
        enhancer.setSuperclass(target.getClass());
        //设置代理对象的回调方法
        enhancer.setCallback(this);
        //创建代理类
        return enhancer.create();
    }

    //回调方法具体实现
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        tx.open();
        Object obj = method.invoke(target, objects);
        tx.commit();
        return obj;
    }
}
